<?php

namespace App\Http\Controllers\Frontend;


use App\Models\Article;
use App\Models\SiteDomain;
use App\Service\Curl;
use Illuminate\Support\Facades\Artisan;
use PhpOffice\PhpWord\PhpWord;

class HomeController extends BaseController
{
    // 首页 初始化
    public function initialize()
    {
        parent::initialize();
    }

    // 首页
    public function index()
    {
        // 获取所有的频道
        $domainDb = new SiteDomain();
        $domain   = $domainDb->isCache(true)->getList(['status' => 1], 0, "id ASC");

        // 总数据量
        $where = [['verify', '=', 1],];
        $model = new Article();
        $total = $model->where($where)->count();

        // 今天数据量
        $cToday = strtotime(date('Y-m-d'));
        $where  = [['verify', '=', 1], ['push_time', '>=', $cToday], ['push_time', '<', $cToday + 86400]];
        $today  = $model->where($where)->count();

        // 昨天数据量
        $cYeday = strtotime("-1 day");
        $where  = [['verify', '=', 1], ['push_time', '>=', $cYeday], ['push_time', '<', $cYeday + 86400]];
        $yeday  = $model->where($where)->count();

        // 昨天的word
        //$cYedate = "2024-3-4";
        $cYedate = date("Y-m-d", $cYeday);
        $newfile = app()->basePath().'/public/'.'date/易见舆情日报'.$cYedate.'.docx';  // 新文件名
        $is_word = is_file($newfile) ? true : false;

        // 传递数据
        $this->assign('is_word', $is_word);
        $this->assign('yesdate', $cYedate);
        $this->assign('sites', $domain);
        $this->assign('totalNumber', $total);
        $this->assign('todayNumber', $today);
        $this->assign('yedayNumber', $yeday);

        return $this->dispaly('index');
    }

    // 获取数据
    public function onLists()
    {
        // 条件
        $is_page = $this->getData('is_page', 0, 'intval');
        $site_id = $this->getData('site_id', 0, 'intval');
        $s_date  = $this->getData('start_date', null, 'trim');
        $e_date  = $this->getData('end_date', null, 'trim');
        $where   = [['verify', '=', 1],];
        if($site_id){
            $where[] = ['site_id', '=', $site_id];
        }
        if($s_date){
            $s_time  = strtotime($s_date);
            $where[] = ['push_time', '>=', $s_time];
        }
        if($e_date){
            $e_time  = strtotime($e_date) + 86400;
            $where[] = ['push_time', '<', $e_time];
        } else{
            if($s_date){
                $where[] = ['push_time', '<', $s_time + 86400];
            }
        }

        // 执行查询
        $model  = new Article();
        $result = $model->listPage($where, $this->page, $this->rows, 'push_time DESC');
        $this->assign('lists', $result['list']);

        // 如果是为了制作翻页
        if($is_page){
            return $this->success($result);
        }

        return $this->dispaly('on-lists');
    }

    // 生成word
    public function makeWord()
    {
        $date     = $this->getData('date', '', 'trim');
        $path     = app()->basePath().'/public/';
        $wordFile = $path.'易见舆情日报.docx';
        $newfile  = $path.'date/易见舆情日报'.$date.'.docx';
        if(!is_file($newfile)){
            // php artisan command:make-word 2024-3-5
            Artisan::call('command:make-word', ['date' => $date]);
        }


        return $this->success([], '生成word成功！');
    }

    // 下载word
    public function downWord()
    {
        // word 信息
        $date     = $this->getData('date', '', 'trim');
        $path     = app()->basePath().'/public/';
        $wordFile = $path.'易见舆情日报.docx';
        $wordFile = $path.'date/易见舆情日报'.$date.'.docx';
        $downfile = $path.'date/易见舆情日报.docx';

        // 股票信息
        $url  = 'https://xinsanban.eastmoney.com/api/QuoteCenter/stock/getstockquote?code=400132';
        $curl = new Curl();
        $res  = $curl->url($url)->request();
        $res  = json_decode($res, true);
        if($res){
            $stock = $res['result'][0] ?? $res['result'];
        }
        if(empty($stock)){
            $stock = ['Close' => '-', 'Change' => '-', 'ChangePercent' => '-', 'MarketValue' => '-',];
        }

        // 方案：直接用模板替换
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);
        $processor->setValue('stock_price', $stock['Close']);
        $processor->setValue('stock_market', $stock['MarketValue'] == '-' ? $stock['MarketValue'] : round($stock['MarketValue'] / 100000000, 2));
        if(($stock['Close'] == '-') && ($stock['Change'] == '-')){
            $processor->setValue('stock_change', '-');
            $processor->setValue('stock_date', '非交易日');
        } else{
            $processor->setValue('stock_date', '交易日');
            $processor->setValue('stock_change', ($stock['ChangePercent'] > 0 ? '+' : '').$stock['ChangePercent']);
        }

        // 保存
        $processor->saveAs($downfile);

        return response()->download($downfile, $date.'易见舆情日报.docx');
    }

    // 股票信息
    public function stock()
    {
        $url  = 'https://xinsanban.eastmoney.com/api/QuoteCenter/stock/getstockquote?code=400132';
        $curl = new Curl();
        $res  = $curl->url($url)->request();
        $res  = json_decode($res, true);
        if(empty($res)){
            return $this->success();
        }

        //var_dump($res['result'][0]['Close']);
        //var_dump($res['result'][0]['ChangePercent']);
        //var_dump($res['result'][0]['MarketValue']);

        return $this->success($res['result'][0] ?? $res['result']);
    }

    // pc端展示翻页
    protected function getPageShow()
    {

    }
}


